package com.zk.config.web.util;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.github.zkclient.ZkClient;
import com.zk.config.web.model.User;
import com.zk.config.web.op.ClientCacheManager;

public class AuthUtils {
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(AuthUtils.class);
	public static final String ZK_USER = "zk_user";
	private static final String USER_FILE_PATH = "user.properties";
	public static Map<String, User> userInfo = new HashMap<>();
	
	static {
		try {
			Properties userProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(USER_FILE_PATH));
			Enumeration<Object> en;
			for(en = userProperties.keys();en.hasMoreElements();) {
				String userName = (String)en.nextElement();
				String pwdRole = userProperties.getProperty(userName);
				if (pwdRole != null) {
					String[] pwdRoleSplit = pwdRole.split(",");
					int role = 0;
					try {
						role = Integer.parseInt(pwdRoleSplit[1]);
					} catch (Exception e) {
					}
					
					User user = new User();
					user.setName(userName);
					user.setPassword(pwdRoleSplit[0]);
					user.setRole(role);
					userInfo.put(userName, user);
				}
			}
		} catch (IOException e) {
			logger.error("没有找到帐号配置文件.{}", e.getMessage(), e);
		}
	}

	public static int isLogin() {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String userName = (String)req.getSession().getAttribute(ZK_USER);
		if (userName != null && userInfo.containsKey(userName)) {
			User user = userInfo.get(userName);
			if (user != null) {
				return user.getRole();
			}
		}
		return 0;
	}

	public static boolean login(String userName, String password, String cxnString, boolean permissOpen) {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		userName = StringUtils.trimToNull(userName);
		password = StringUtils.trimToNull(password);
		if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
			return false;
		}
		User user = userInfo.get(userName);
		if(user != null) {
			if (StringUtils.equals(password, user.getPassword())) {
				req.getSession().setAttribute(ZK_USER, userName);
				
				if(permissOpen) {
					String key = ClientCacheManager.PRE + cxnString;
					Object obj = req.getSession().getAttribute(key);
					if(obj != null) {
						ZkClient zkClient = (ZkClient)obj;
						if(zkClient != null) {
							try {
								zkClient.getZooKeeper().close();
							} catch (InterruptedException e) {
								e.printStackTrace();
								logger.error(e.getMessage());
							}
							zkClient.close();
							zkClient = null;
							req.getSession().removeAttribute(key);
						}
					}
				}
				return true;
			}
		}
		return false;
	}
	
	public static boolean logout(String cxnString, boolean permissOpen) {
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		req.getSession().removeAttribute(ZK_USER);
		if(permissOpen) {
			String key = ClientCacheManager.PRE + cxnString;
			Object obj = req.getSession().getAttribute(key);
			if(obj != null) {
				ZkClient zkClient = (ZkClient)obj;
				if(zkClient != null) {
					try {
						zkClient.getZooKeeper().close();
					} catch (InterruptedException e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
					zkClient.close();
					zkClient = null;
					req.getSession().removeAttribute(key);
				}
			}
		}
		return true;
	}
}
